package se.hiq.wineo.client;

import se.hiq.wineo.client.events.WineListLoadedEvent;
import se.hiq.wineo.client.events.WineUpdatedEvent;
import se.hiq.wineo.client.events.WineUpdatedEventHandler;
import se.hiq.wineo.client.widgets.WineFilter;
import se.hiq.wineo.client.widgets.WineFilterWidget;
import se.hiq.wineo.client.widgets.WineListWidget;
import se.hiq.wineo.client.widgets.WineStatWidget;
import se.hiq.wineo.client.widgets.WineViewWidget;
import se.hiq.wineo.shared.data.WineDescriptor;
import se.hiq.wineo.shared.data.WineDetails;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class WineO implements EntryPoint {

	//Create a remote service proxy to talk to the server-side Greeting service.
	private final WineServiceAsync wineService = GWT.create(WineService.class);

	private HandlerManager eventBus = new HandlerManager(null);
	
	// Widgets
	private WineListWidget wineList = null;
	private WineViewWidget wineView = null;
	private WineStatWidget wineStat = null;
	private WineFilter wineFilter = null;
	
	// This is the entry point method.
	public void onModuleLoad() {
		// Run these first to reduce loading time of this applet
		requestCompleteWineList();
		
		wineList = new WineListWidget(eventBus);
		wineView = new WineViewWidget(eventBus);
		wineStat = new WineStatWidget(eventBus);
		
		RootPanel.get("wineList").add(wineList);
		RootPanel.get("wineView").add(wineView);
		RootPanel.get("wineStat").add(wineStat);
		
		wineFilter = new WineFilter(eventBus, new WineFilterWidget(), wineService);
		wineFilter.attach(RootPanel.get("wineMVP"));
		
		initHandlers();
	}
	
	private void initHandlers() {
		// Add this to ensure that all data on screen is up to date with what's in the database
		eventBus.addHandler(WineUpdatedEvent.TYPE, new WineUpdatedEventHandler() {
			@Override
			public void onWineUpdatedEvent(WineDetails wine) {
				// Update this
				requestCompleteWineList();
			}
		});
	}
	
	private void requestCompleteWineList() {
		wineService.getAvailableWines(new AsyncCallback<WineDescriptor[]>() {
			@Override
			public void onSuccess(WineDescriptor[] result) {
				eventBus.fireEvent(new WineListLoadedEvent(result));
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error: " + caught.toString());
			}
		});
	}
	
}
